package com.gitee.limaozhi.socket.lesson03.example3;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * 客户端业务处理器
 *
 * @author hzlimaozhi
 * @date 2019/08/07 11:44
 */
public class ClientLogicHandler extends HandlerAdapter {

    private int prevReq = -1;
    private AtomicInteger req = new AtomicInteger(0);
    private boolean fireFinish = false;

    @Override
    public Handler start() {
        next().handle("你好");
        next().handle("今天天气怎么样？");
        next().handle("现在什么时间？");
        next().handle("明天温度多少？");
        next().handle("拜拜");
        next().finish(5);
        return this;
    }

    @Override
    public Handler handle(Object object) {
        context().print(context().getName() + "：收到：" + object);
        req.incrementAndGet();
        fireFinish();
        return this;
    }

    @Override
    public Handler finish(int prevReq) {
        this.prevReq = prevReq;
        fireFinish();
        return this;
    }

    private synchronized void fireFinish() {
        if (!fireFinish) {
            if (prevReq == req.get()) {
                fireFinish = true;
//                context().print(context().getName() + "：ClientLogic：" + req.get());
                context().close();
            }
        }
    }

}
